package com.sd.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import android.content.Context;
import android.os.Handler;

import com.alex.books.BaseBook;
import com.alex.database.BookDao;
import com.sd.app.AppInit;
import com.sd.database.BookInfo;

public class FirstDo {

	private Handler mHandler;
	private String DB_PATH = AppInit.getInstance().APP_BOOKS;

	private String mTagertZip = DB_PATH + "r.zip";

	// private String mTagertZip = DB_PATH+"test.zip";

	public void start(Context context, Handler hander) {

		mHandler = hander;

		mHandler.sendEmptyMessage(1);
		// 复制资源文件到指定目录下
		try {
			copyBigDataBase(context);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessage(2);
		File f = new File(mTagertZip);
		/*
		 * try { new ZipUtils().upZipFile(f, DB_PATH); } catch (ZipException e)
		 * { // TODO Auto-generated catch block e.printStackTrace(); } catch
		 * (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		try {
			new ZipUtil().unZip(mTagertZip, DB_PATH, true);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		mHandler.sendEmptyMessage(3);

		// 将书导入到数据库中
		insertBoutiqueBook(context);

	}

	public void copyBigDataBase(Context context) throws IOException {
		InputStream myInput;
		String outFileName = DB_PATH;

		String[] files = context.getAssets().list("books");
		for (int i = 0; i < files.length; i++) {
			OutputStream myOutput = new FileOutputStream(outFileName + files[i]);
			myInput = context.getAssets().open("books/" + files[i]);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}
			myOutput.flush();
			myInput.close();
			myOutput.close();
		}
	}

	/**
	 * 给定根目录，返回一个相对路径所对应的实际文件名.
	 * 
	 * @param baseDir
	 *            指定根目录
	 * @param absFileName
	 *            相对路径名，来自于ZipEntry中的name
	 * @return java.io.File 实际的文件
	 */
	public static File getRealFileName(String baseDir, String absFileName) {
		String[] dirs = absFileName.split("/");
		File ret = new File(baseDir);
		String substr = null;
		if (dirs.length > 1) {
			for (int i = 0; i < dirs.length - 1; i++) {
				substr = dirs[i];
				try {
					// substr.trim();
					substr = new String(substr.getBytes("8859_1"), "GB2312");

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ret = new File(ret, substr);

			}
			if (!ret.exists())
				ret.mkdirs();
			substr = dirs[dirs.length - 1];
			try {
				// substr.trim();
				substr = new String(substr.getBytes("8859_1"), "GB2312");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			ret = new File(ret, substr);
			return ret;
		}
		return ret;
	}

	private void insertBoutiqueBook(Context context) {

		BookInfoHandle handle = new BookInfoHandle();
		Vector<BookInfo> books = handle.getBooksInfo(context);

		File dir = new File(DB_PATH);
		String[] files = dir.list();
		for (int i = 0; i < files.length; i++) {
			String url = DB_PATH + files[i];
			BaseBook book = new BaseBook();
			book.mBookName = url.substring(url.lastIndexOf("/") + 1, url
					.lastIndexOf("."));
				if (url.endsWith(".sbn") || url.endsWith(".qd")) {
				book.mBookPath = url;
				for (int j = 0; j < books.size(); j++) {
					BookInfo bookinfo = books.get(j);
					if (bookinfo.bookName.equals(book.mBookName)) {
						book.mWordNumber = bookinfo.wordNumber;
						// book.mChapterNumber = bookinfo.chapterNumber;
						book.mBookAuthor = bookinfo.author;
						book.mAboutAuthor = bookinfo.aboutAuthor;
						book.mSource = bookinfo.source;
						book.mAboutBook = bookinfo.aboutBook;
						book.mBookCover = bookinfo.coverUrl;
						book.mBookSerial = bookinfo.bookSerial;
						book.mAttach1 = "" + 1;
						book.mAttach2 = "" + 0;
					}
				}
				book.mBookId = (int) BookDao.getInstance()
						.insertBook(context, book);
			}
			}
	}
}
